package com.mj.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/download.do")
public class Download extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String filename = req.getParameter("name");
        String downname = new SimpleDateFormat("yyMMddhhmmss").format(new Date())+filename.substring(filename.lastIndexOf(".")).toLowerCase();
        String path = req.getServletContext().getRealPath("/download/");
        //设置响应头和客户端的文件名
        resp.setContentType("multipart/form-data");
        resp.setHeader("Content-Disposition", "attachment;fileName=" + downname);
        InputStream is = new FileInputStream(path + filename);
        OutputStream os = resp.getOutputStream();
        byte[] b = new byte[10240];//缓存
        int i = 0;
        while ((i = is.read(b)) > 0) {
            os.write(b, 0, i);//如果读取到东西，就写入输出
        }
        os.flush();
        os.close();
        is.close();
    }
}
